package com.xyz.code.builder.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import com.xyz.code.bean.MetaDataBean;
import com.xyz.code.builder.AbstractBuilder;
import com.xyz.code.util.MyFileUtil;

public class MapperXmlBuilder extends AbstractBuilder {

	public MapperXmlBuilder(String tableName, String packageName,
			String outFileName, Map<String, String> map) {
		bean = new MetaDataBean(tableName, packageName, outFileName, map);
	}

	@Override
	public void builder() {
		String str = "";
		try {
			str = MyFileUtil.getContextByTemplate(this, getTemplate());
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {

			OutputStreamWriter write = new OutputStreamWriter(
					new FileOutputStream(new File(
							getBaseDir() + bean.getClassName() + "Mapper.xml")),
					"UTF-8");
			BufferedWriter writer = new BufferedWriter(write);
			writer.write(str);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String getBaseDir() {
		String[] paths = bean.getBasePackage().split("\\.");
		String fileDir = "out/service/src/main/resources/";
		for (String path : paths) {
			fileDir = fileDir + path + "/";
		}
		fileDir += "domain/mapper/";
		File file = new File(fileDir);
		file.mkdirs();
		return fileDir;
	}

	@Override
	public String getTemplate() {
		// TODO Auto-generated method stub
		return "template/model/domain/mapper/${className}Mapper.xml";
	}

}
